"""
dict 服务端
"""
import sys
from multiprocessing import Process
from socket import *

from day18.dict_db import Dict

class Handle:
    def __init__(self, connfd):
        self.connfd = connfd
        self.name = ""

    def register(self, name, password):
        if db.register(name, password):
            self.connfd.send(b"ok")
        else:
            self.connfd.send(b"FAIL")

    def login(self, name, password):
        if db.login(name, password):
            self.connfd.send(b'ok')
            self.name = name
        else:
            self.connfd.send(b"FAIL")

    def query(self, words, name):
        mean = db.query(words, name)
        self.connfd.send(mean.encode())

    def history(self,name):
        record = db.history(name)
        self.connfd.send(record.encode())

    # 客户端处理
    def handle(self):
        # 总分结构
        while True:
            data = self.connfd.recv(1024)  # 接收请求
            temp = data.decode().split(" ")
            # 分情况套路
            if not data or temp[0] == 'E':
                break
            if temp[0] == 'R':
                result = self.register(temp[1], temp[2])
            elif temp[0] == "L":
                result = self.login(temp[1], temp[2])
            elif temp[0] == "Q":
                result = self.query(temp[1], self.name)
            elif temp[0] == "H":
                result = self.history(self.name)


# 创建进程
class ProcessServer(Process):
    def __init__(self, connfd):
        self.connfd = connfd
        self.handle = Handle(connfd)
        super().__init__()

    def run(self):
        db.cursor()
        self.handle.handle()
        db.cur.close()
        self.connfd.close()


# 创建tcp网络模型
class DictServer:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self._create_socket()

    def _create_socket(self):
        sock = socket()
        sock.bind(self.address)
        return sock

    def serve_forever(self):
        self.sock.listen(5)
        print("Listen the port %d" % self.port)
        # 　循环处理客户端连接
        while True:
            try:
                connfd, addr = self.sock.accept()
                print("Connect from", addr)
            except KeyboardInterrupt:
                db.close()
                self.sock.close()
                sys.exit("服务结束")
            # 创建进程
            p = ProcessServer(connfd)
            p.start()


if __name__ == '__main__':
    dict = DictServer(host="0.0.0.0", port=8000)
    db = Dict()  # 全局变量
    dict.serve_forever()
